package com.yjt.termworks.fragment;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.Image;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yjt.termworks.LoginActivity;
import com.yjt.termworks.R;
import com.yjt.termworks.entity.HomeCircle;
import com.yjt.termworks.sql.MyHelper;
import com.yjt.termworks.utils.ImageLoaderUtils;
import com.yjt.termworks.utils.SharePreferenceData;

import java.util.ArrayList;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MineFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MineFragment extends Fragment {
    private int currentAvatarIndex = 0;
    private int[] avatarList = {R.drawable.avatar, R.drawable.tou1, R.drawable.tou2};
    private CircleImageView profilePicture;
    private  ImageView iv;
    private Button logout_btn;
//    private String baseImageUrl=R.string.baseImageUrl+"";
    private String baseImageUrl = "http://10.175.253.209:9002/images/userAvatar/";

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MineFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MineFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MineFragment newInstance(String param1, String param2) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_mine, container, false);

        // 显示个人信息
        getData(rootView);
        logout_btn = rootView.findViewById(R.id.logout_btn);
        logout_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(view.getContext(), LoginActivity.class);
                startActivity(intent);
            }
        });
        // 跳转过来的处理事件


        //

        CircleImageView profilePicture = rootView.findViewById(R.id.profile_picture);
        ImageView iv = rootView.findViewById(R.id.profile_bg);
        final String[] itemLabels = {"图片1", "图片2", "图片3"};
        final int[] itemImages = {R.drawable.avatar, R.drawable.tou1, R.drawable.tou2};
        final int defaultAvatarIndex = 0;
        final int[] currentAvatarIndex = {defaultAvatarIndex};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.item_avatar, itemLabels) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_avatar, parent, false);
                ImageView imageView = convertView.findViewById(R.id.avatar_image_view);
                imageView.setImageResource(itemImages[position]);
                return convertView;
            }
        };

        // 设置初始头像图片
        profilePicture.setImageResource(itemImages[currentAvatarIndex[0]]);
        iv.setImageResource(itemImages[defaultAvatarIndex]);

        // 打开选择头像的弹窗
        profilePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("选择头像");
                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        currentAvatarIndex[0] = which; // 更新选中的头像下标
                        profilePicture.setImageResource(itemImages[currentAvatarIndex[0]]);
                    }
                });
                builder.show();
            }
        });

        // 打开选择背景图片的弹窗
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("选择背景图片");
                builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        iv.setImageResource(itemImages[which]);
                    }
                });

                builder.show();
            }
        });

        return rootView;
    }

    public void getData(View view){
        MyHelper myHelper = new MyHelper(view.getContext());
        SQLiteDatabase db = myHelper.getWritableDatabase();

        Map<String, String> userInfo;
        String userPhone;
        userInfo = SharePreferenceData.getUserData2(view.getContext());

        if(userInfo.get("phone") != null){
            userPhone = userInfo.get("phone");
        }else{
            userInfo = SharePreferenceData.getUserData(view.getContext());
            userPhone = userInfo.get("userName");
        }

        ContentValues values = new ContentValues();
        Cursor cursor = db.rawQuery("select * from USER where phone = ?", new String[]{userPhone});
        try {
            if (cursor.moveToFirst()) {
                TextView name = view.findViewById(R.id.profile_name);
                name.setText(cursor.getString(1));
                CircleImageView vie = view.findViewById(R.id.profile_picture);
                ImageView bg = view.findViewById(R.id.profile_bg);
                ImageLoaderUtils.display(view.getContext(),vie,baseImageUrl+cursor.getString(4));
                ImageLoaderUtils.display(view.getContext(),bg,baseImageUrl+cursor.getString(5));

                Cursor cursor1 = db.rawQuery("select * from CIRCLE where username = ?", new String[]{cursor.getString(1)});
                if(cursor1.moveToFirst()){
                    TextView text = view.findViewById(R.id.circleMsg);
                    text.setText(cursor1.getString(4));
                    TextView like = view.findViewById(R.id.likeNum);
                    like.setText(cursor1.getString(5));
                    TextView comment = view.findViewById(R.id.circleComment);
                    comment.setText(cursor1.getString(6));
                }

            } else {
                Toast.makeText(view.getContext(), "查询失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }
}